package com.ewing.busi.order.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.ObjectUtils;
import org.apache.log4j.Logger;

import com.ewing.busi.carry.dto.WebCarryWayResp;
import com.ewing.busi.carry.service.WebCarryService;
import com.ewing.busi.customer.dto.LightAddressInfoResp;
import com.ewing.busi.customer.service.CustomerAddressService;
import com.ewing.busi.order.constants.OrderStatus;
import com.ewing.busi.order.dto.AddOrdeReq;
import com.ewing.busi.order.dto.CommitOrdeReq;
import com.ewing.busi.order.dto.ConfirmOrderReq;
import com.ewing.busi.order.dto.ConfirmOrderReq.Item;
import com.ewing.busi.order.dto.LightOrderInfoReq;
import com.ewing.busi.order.dto.LightOrderInfoResp;
import com.ewing.busi.order.dto.OrderInfoDetailReq;
import com.ewing.busi.order.dto.OrderInfoDetailResp;
import com.ewing.busi.order.model.OrderInfo;
import com.ewing.busi.order.service.OrderCartService;
import com.ewing.busi.order.service.OrderDetailService;
import com.ewing.busi.order.service.OrderInfoService;
import com.ewing.busi.resource.action.WebResourceAction;
import com.ewing.busi.resource.helper.PayWayHelper;
import com.ewing.busi.seller.service.SellerShopService;
import com.ewing.common.constants.AjaxRespCode;
import com.ewing.common.constants.ResponseCode;
import com.ewing.common.exception.BusinessException;
import com.ewing.core.app.action.base.BaseAction;
import com.google.common.collect.Maps;

/**
 * 订单的相关操作
 * 
 * @author Joeson Chan<chenxuegui1234@163.com>
 * @since 2016年2月2日
 */
public class OrderInfoAction extends BaseAction {

  /**
   * 
   * created by Joeson on 2016年4月24日 下午4:45:31
   */
  private static final long serialVersionUID = 1L;
  private static Logger logger = Logger.getLogger(WebResourceAction.class);
  @Resource
  private OrderCartService orderCartService;
  @Resource
  private OrderDetailService orderDetailService;
  @Resource
  private OrderInfoService orderInfoService;
  @Resource
  private CustomerAddressService customerAddressService;
  @Resource
  private WebCarryService webCarryService;
  @Resource
  private SellerShopService sellerShopService;


  /**
   * 获取首页产品列表
   */
  // @CustomerLoginFilter
  public void queryIndexOrder() {
    try {
      LightOrderInfoReq request = getParamJson(LightOrderInfoReq.class);
      Integer page = request.getPage();
      Integer pageSize = request.getPageSize();

      List<LightOrderInfoResp> list =
          orderInfoService.queryByCusId(getLoginCusId(), getShopIdInt(), request.convertStatus(), page, pageSize);
      Map<String, Object> map = Maps.newHashMap();
      map.put("list", list);
      map.put("payWays", PayWayHelper.list());
      outSucResult(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  /**
   * 根据id查找detail 场景：提交订单前进行订单的load
   * 
   * @author Joeson
   */
  public void getById() {
    try {
      OrderInfoDetailReq req = getParamJson(OrderInfoDetailReq.class);
      Integer orderId = req.getOrderId();
      checkRequired(orderId, "orderId");

      OrderInfo orderInfo = orderInfoService.findByIdAndCusId(orderId, getLoginCusId());
      List<OrderInfoDetailResp> list =
          orderDetailService.findByOrderIdAndCusId(orderId, getLoginCusId(), getShopIdInt());
      LightAddressInfoResp defaultAddr = customerAddressService.findDefaultAddress(getLoginCusId());
      List<LightAddressInfoResp> addrList = customerAddressService.queryByCusId(getLoginCusId());
      List<WebCarryWayResp> wayDtoMap = webCarryService.findByOrderIdAndRegion(getLoginCusId(),
          req.getOrderId(), defaultAddr.getCity());

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("list", list);
      map.put("addrList", addrList);
      map.put("payWays", PayWayHelper.list());
      map.put("defaultAddr", defaultAddr);
      map.put("carryWay", wayDtoMap);
      map.put("isCommit",
          null != orderInfo
              && (ObjectUtils.equals(orderInfo.getStatus(), OrderStatus.INIT.getValue())
                  || ObjectUtils.equals(orderInfo.getStatus(), OrderStatus.WAIT_PAY.getValue())));
      outSucResult(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  /**
   * 根据id查找detail 场景：提交订单后，对订单进行查询
   * 
   * @author Joeson
   */
  public void getDetailById() {
    try {
      OrderInfoDetailReq req = getParamJson(OrderInfoDetailReq.class);
      Integer orderId = req.getOrderId();
      checkRequired(orderId, "orderId");

      Integer cusId = getLoginCusId();
      List<OrderInfoDetailResp> list = orderDetailService.findByOrderIdAndCusId(orderId, cusId, getShopIdInt());
      LightAddressInfoResp orderAddr = orderInfoService.getOrderAddress(orderId, cusId);
      List<WebCarryWayResp> wayDtoMap =
          webCarryService.findByOrderIdAndRegion(cusId, req.getOrderId(), orderAddr.getCity());

      com.ewing.busi.resource.helper.PayWayHelper.Item item =
          orderInfoService.getPayWay(orderId, cusId);

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("list", list);
      map.put("payWays", Arrays.asList(item));
      map.put("orderAddr", orderAddr);
      map.put("carryWay", wayDtoMap);
      outSucResult(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  /**
   * 确认订单
   * 
   * @author Joeson
   */
  public void confirmOrder() {
    try {
      ConfirmOrderReq req = getParamJson(ConfirmOrderReq.class);
      List<Item> list = new ArrayList<Item>();
      checkRequired(list, "list");

      orderInfoService.confirmOrder(req);
      // @TODO 抽取dto对象
      // List<OrderInfoDetailResp> list = orderInfoService.getById(orderId);
      // Map<String, Object> map = new HashMap<String, Object>();
      // map.put("list", list);
      // map.put("payWay", PayWay.values());
      // map.put("shopName", SystemPropertyUtil.getShopName());
      // outSucResult(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  /**
   * 关闭订单
   * 
   * @author Joeson
   */
  public void closeOrder() {
    try {
      OrderInfoDetailReq req = getParamJson(OrderInfoDetailReq.class);
      Integer orderId = req.getOrderId();
      checkRequired(orderId, "orderId");

      orderInfoService.closeOrder(getLoginCusId(), orderId);
      outSucResult(ResponseCode.OK);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  public void addOrder() {
    try {
      AddOrdeReq req = getParamJson(AddOrdeReq.class);
      checkRequired(req, "入参不能为空");

      Integer orderId = orderInfoService.addOrder(getLoginCusId(), req);
      Map<String, Object> map = Maps.newHashMap();
      map.put("orderId", orderId);
      outSucResult(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }

  /**
   * 提交订单
   * 
   * @author Joeson
   */
  public void commitOrder() {
    try {
      CommitOrdeReq req = getParamJson(CommitOrdeReq.class);
      checkRequired(req, "入参不能为空");

      // 如果没有设置默认地址，需要先进行默认设置
      if (!customerAddressService.existDefaultAddress(getLoginCusId())) {
        outSucResult(AjaxRespCode.ORDER_UN_EXISTS_ADDRESS.code);
        return;
      }

      boolean result = orderInfoService.commitOrder(getLoginCusId(), req);
      if (result) {
        outSucResult(AjaxRespCode.CODE_SUC.code);
      } else {
        outFailResult(AjaxRespCode.CODE_ERROR);;
      }
    } catch (BusinessException e) {
      outAlert(e.getMessage());
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outFailResult("内部异常");
    }
  }
}
